package top.bingoz.wanandroid.ui.activity

import android.content.Context
import kotlinx.android.synthetic.main.act_images2.*
import top.bingoz.wanandroid.R
import top.bingoz.wanandroid.base.BaseActivity
import top.bingoz.wanandroid.bean.Images
import top.bingoz.wanandroid.data.http.observer.SimpleSubscriber
import top.bingoz.wanandroid.data.http.transformer.SimpleTransformer
import top.bingoz.wanandroid.di.module.HttpModule
import top.bingoz.wanandroid.ui.adapter.ImageAdapter


class Images2Activity : BaseActivity() {

    val mContext: Context = this

    var page: Int = 0

    private lateinit var mImgsAdapter: ImageAdapter


    override fun getLayoutId(): Int {
        return R.layout.act_images2
    }

    override fun initialize() {

        mImgsAdapter = ImageAdapter(mContext)

        recyclerView.addAdapter(mImgsAdapter)


        recyclerView.setOnRefreshListener {
            refreshData()

        }


        recyclerView.setOnLoadMoreListener {
            page++
            HttpModule.apiService(mContext).queryImages(page)
                    .compose<Images>(SimpleTransformer(provider.bindToLifecycle()))
                    .subscribe(object :SimpleSubscriber<Images>(){
                        override fun onNext(data: Images) {
                            super.onNext(data)

                            recyclerView.loadFinish(false)

                            mImgsAdapter.addDatas(data.data)

                        }

                        override fun onError(e: Throwable) {
                            super.onError(e)
                            recyclerView.loadFinish(false)
                        }
                    })

        }

        refreshData()
    }

    private fun refreshData() {
        page = 0
        HttpModule.apiService(mContext).queryImages(page)
                .compose<Images>(SimpleTransformer(provider.bindToLifecycle()))
                .subscribe(object : SimpleSubscriber<Images>() {
                    override fun onNext(data: Images) {
                        super.onNext(data)

                        recyclerView.loadFinish(true)

                        mImgsAdapter.setDatas(data.data)

                    }

                    override fun onError(e: Throwable) {
                        super.onError(e)
                        recyclerView.loadFinish(true)
                    }
                })
    }


}
